<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\kuaishou;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\model\ClientAccountModel;
use app\model\KsOcpxConversionModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\kuaishou\AdvertiserService;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

final class OcpxConversionDeepTypesService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::LIST_CONFIG_LOCK_KEY]['ocpx_conversion_deep_types'];

    public static function getOcpxConversionDeepTypes(string $advertiserId = ''): bool
    {
        try {
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            // 获取优化目标
            $ocpxActionTypes = self::getActionOcpx($advertiserId);
            if (! $ocpxActionTypes) {
                return true;
            }
            foreach ($ocpxActionTypes as $actionType) {
                $params = [
                    'scene_category' => $actionType['scene_category'],
                    'campaign_type' => $actionType['campaign_type'],
                    'scene_ids' => [$actionType['scene_ids']],
                    'app_id' => $actionType['app_id'],
                    'ocpx_action_type' => $actionType['ocpx_action_type'],
                ];
                $result = self::getList($advertiserId, $params);
                if ($result === false) {
                    return false;
                }
                if (count($result['data']['deep_types']) == 0) {
                    continue;
                }
                $actionType->setAttr('deep_types', json_encode($result['data']['deep_types'], JSON_UNESCAPED_UNICODE));
                if (! $actionType->save()) {
                    throw new \Exception('保存深度出错');
                }
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取浅度优化目标.
     * @param string $advertiserId 账户id
     * @return array|Collection|KsOcpxConversionModel[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getActionOcpx(string $advertiserId = '')
    {
        return (new KsOcpxConversionModel())->where('advertiser_id', $advertiserId)->select();
    }


    /**
     * 拉取深度出价.
     *
     * @param string $advertiserId 账户id
     * @param array $params 深度参数
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', array $params = [])
    {
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params['advertiser_id'] = $advertiserId;
        return AdvertiserService::getOcpxConversionDeepTypes($headers, $params);
    }
}
